package biz.t8.blog.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import biz.t8.blog.dto.LogActions;
import biz.t8.blog.modal.Bo.RestResponseBo;
import biz.t8.blog.modal.Vo.UserVo;
import biz.t8.blog.service.ILogService;
import biz.t8.blog.service.IUserService;
import biz.t8.blog.utils.DateKit;
import biz.t8.blog.utils.TaleUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import biz.t8.blog.constant.WebConst;
import biz.t8.blog.exception.TipException;

/**
 * 前台登录/登出
 * Ceated by cnxk 2019-12-01
 */
@Controller
@RequestMapping("/user")
@Transactional(rollbackFor = TipException.class)
public class UserController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Resource
    private IUserService usersService;

    @Resource
    private ILogService logService;

    @GetMapping(value = "/login")
    public String login() {
        return "user/login";
    }
    
    @GetMapping(value = "/register")
    public String register() {
        return "user/register";
    }

    /**
     * 管理后台登录
     * @param username
     * @param password
     * @param remeber_me
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "login")
    @ResponseBody
    public RestResponseBo doLogin(@RequestParam String username,
                                  @RequestParam String password,
                                  @RequestParam(required = false) String remeber_me,
                                  HttpServletRequest request,
                                  HttpServletResponse response) {

        Integer error_count = cache.get("login_error_count");
        try {
            UserVo user = usersService.login(username, password);
            request.getSession().setAttribute(WebConst.LOGIN_SESSION_KEY, user);
            if (StringUtils.isNotBlank(remeber_me)) {
                TaleUtils.setCookie(response, user.getUid());
            }
            logService.insertLog(LogActions.LOGIN.getAction(), null, request.getRemoteAddr(), user.getUid());
        } catch (Exception e) {
            error_count = null == error_count ? 1 : error_count + 1;
            if (error_count > 3) {
                return RestResponseBo.fail("您输入密码已经错误超过3次，请10分钟后尝试");
            }
            cache.set("login_error_count", error_count, 10 * 60);
            String msg = "登录失败";
            if (e instanceof TipException) {
                msg = e.getMessage();
            } else {
                LOGGER.error(msg, e);
            }
            return RestResponseBo.fail(msg);
        }
        return RestResponseBo.ok();
    }

    /**
     * 注销
     * @param session
     * @param response
     */
    @RequestMapping("/logout")
    public void logout(HttpSession session, HttpServletResponse response, HttpServletRequest request) {
        session.removeAttribute(WebConst.LOGIN_SESSION_KEY);
        Cookie cookie = new Cookie(WebConst.USER_IN_COOKIE, "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        try {
            response.sendRedirect("/");
            //response.sendRedirect(Commons.site_login());
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error("注销失败", e);
        }
    }
    
    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.POST)
	public RestResponseBo doRegister(@RequestParam(required = true) String username,
            @RequestParam(required = true) String email,
            @RequestParam(required = true) String password,
            @RequestParam(required = true) String repassword,
            ServletRequest request, ServletResponse response) {
    	 
		if (!password.contentEquals(repassword)) {
			return RestResponseBo.fail("两次输入密码不一致,请重新输入!");
		}
		UserVo userVo = usersService.queryUserByName(username);
		if (userVo != null) {
			return RestResponseBo.fail("此用户已存在!");
		}
		UserVo vo = new UserVo();
		vo.setUsername(username);
		vo.setPassword(password);
		vo.setCreated(DateKit.getCurrentUnixTime());
		vo.setEmail(email);
		vo.setUserType(WebConst.REGISTER_USER);
		usersService.insertUser(vo);
		return RestResponseBo.ok();
	}
    
}